package com.mit.wx.service.impl;

import com.mit.wx.dao.BaseDao;
import com.mit.wx.dao.WxUserDao;
import com.mit.wx.entity.WxUser;
import com.mit.wx.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 2018/10/9 Create by 郭文梁
 * WxUserServiceImpl
 * 微信用户服务实现类
 *
 * @author 郭文梁
 * @date 2018/10/9
 */
@Service
public class WxUserServiceImpl extends BaseServiceImpl<WxUser> implements WxUserService {
    /**
     * 48小时之内活动的用户允许发送客服消息
     */
    private static final int READY_FOR_SENDING_HOURS = 48;
    private final WxUserDao wxUserDao;

    @Autowired
    public WxUserServiceImpl(WxUserDao wxUserDao) {
        this.wxUserDao = wxUserDao;
    }

    @Override
    public BaseDao<WxUser> getRepository() {
        return wxUserDao;
    }

    @Override
    public void saveIfNotExists(String openId) {
        WxUser user = wxUserDao.findByOpenId(openId);
        if (user == null) {
            final Date now = new Date();
            user = new WxUser();
            user.setOpenId(openId);
            user.setLastActivityTime(now);
            user.setLogUpDate(now);
            wxUserDao.save(user);
        }
    }

    @Override
    public List<WxUser> ready4Sending() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR, 0 - READY_FOR_SENDING_HOURS);
        return wxUserDao.findByLastActivityTimeAfter(calendar.getTime());
    }
}
